<template>
  <div class='app-container'>
    <div class='app-box clear'>
      <div class='inputbox'>
        <div class="day-top clearfix">
         <div class="top">
                <span>出单时间：</span>
              
                  <!-- {{time1}} -->
                  <el-date-picker
                    v-model="time1"
                    type="daterange"
                    range-separator="至"
                    size="mini"
                    clearable
                    prefix-icon=''
                    
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
              </div>
			    <div class="top2">
            <span>保险公司：</span>
            <el-select class="wid" size="mini" v-model="Insurance" placeholder="请选择保险公司" multiple collapse-tags>
              <el-option-group v-for="group in companies" :key="group.letter" :label="group.letter">
                <el-option v-for="item in group.insurances" :key="item.id" :label="item.insuranceName" :value="item.id">
                </el-option>
              </el-option-group>
            </el-select>
          </div>
          <div class="top1">
            <span>所属机构：</span>
            <!-- <ztree-select class="wd210" v-model="organizationUnitId" :treedata="treeData" :childprops="childprops" @change='setSelectedId'></ztree-select> -->
            <el-select v-model="organizationUnitId" placeholder="请选择" size="mini" class="wd210">
              <el-option v-for="item in treeData" :key="item.organizationId" :label="item.organizationName" :value="item.organizationId">
              </el-option>
            </el-select>
          </div>
        
          <el-dropdown split-button type="primary" @click="toSearch" size="mini" style="height:29px;" placement='bottom-end' class="day-dropdown" @command='exportForm'>
            查询
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item style="width:87px; text-align:center;">导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <!-- <div class="unitbox"><span>(单位：万元)</span></div> -->
      <div class="cenVal">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            {{allSelect}}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="1">保单量</el-dropdown-item> -->
            <el-dropdown-item command="1">总保费（万元）</el-dropdown-item>
            <el-dropdown-item command="2">净保费（万元）</el-dropdown-item>
            <el-dropdown-item command="3">总收入（万元）</el-dropdown-item>
            <el-dropdown-item command="4">总支出（万元）</el-dropdown-item>
            <el-dropdown-item command="5">利润（万元）</el-dropdown-item>
            <el-dropdown-item command="6">利润率（百分比）</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- 列表 -->
      <div class=" bustable">
        <el-table :data="tableData3" header-align="left" align="right" stripe type="index" v-loading="loading" style="width: 100%">
          <el-table-column fixed align="center" :render-header="renderHeader" width="130" class="baixianG">
            <template slot-scope="scope">
              <span @click="toMonthForm(scope.row.insuranceId)" style="cursor:pointer;" class="ishover">{{scope.row.insuranceName}}</span>
            </template>

          </el-table-column>

          <el-table-column align="center" v-for="(col,index) in columns2" :key="col.value" :prop="col.value" :label="col.value" min-width="130px">
            <el-table-column v-for="(item,indexItem) in col.items"  :key="item" :prop="item" :label="item" min-width="90px" align="right" >
              <template slot-scope="scope">
                 <!-- <span>{{index}},{{indexItem}}</span> -->
                 <span>{{col}},{{item}}</span>
              </template>
            </el-table-column>

          </el-table-column>
         
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import ztreeSelect from "@/components/z-select/index.vue";
export default {
  components: {
    ztreeSelect
  },
  filters: {
    keepTwoNum: function(val) {
      val = Number(val);
      return val.toFixed(2);
    },
    format: function(val) {
      val = val.replace('年','y')
      val = val.replace('月','m')
      return val;
    }
  },
  data() {
    return {
      time1: "",
      time2: "",
      // endDateOpt: this.enddate(),
      // startDateOpt: this.startdate(),
      insuranceId: "",
      companies: [],
      treeData: [],
      //数组子级相关参数
      childprops: {
        name: "displayName", //显示名字
        children: "organizationUnits", //子级字段名
        lv: "level" //当前层级
      },
      organizationUnitId: "",
      type1: "0",
      Insurance: [],
      loading: false,
      allSelect: "总保费",
      options: [
      
        {
          value: "1",
          label: "总保费"
        },
        {
          value: "2",
          label: "净保费"
        },
        {
          value: "3",
          label: "总收入"
        },
        {
          value: "4",
          label: "总支出"
        },
        {
          value: "5",
          label: "利润"
        },
        {
          value: "6",
          label: "利润率"
        }
      ],
      value5: '2',
      //数据类型选项
      columns: [
        {value:'保单量',items:['总量','交强险','商业险']},
        {value:'总费用（万元）',items:['总保费','净保费','总收入','总支出','利润','利润率']},
        {value:'交强险保费（万元）',items:['总保费','净保费','总收入','总支出','利润','利润率']},
		{value:'商业险保费（万元）',items:['总保费','净保费','总收入','总支出','利润','利润率']},
		{value:'车船税费用（万元）',items:['总保费','净保费','总收入','总支出','利润','利润率']}
		
	  ],
	  columns2: [
        {value:'保单量',items:['总量','交强险','商业险']},
        {value:'总费用（万元）',items:['总保费']},
        {value:'交强险保费（万元）',items:['总保费']},
		{value:'商业险保费（万元）',items:['总保费']},
		{value:'车船税费用（万元）',items:['总保费']}
		
      ],
      //列表数据
      tableData3: [

			{
				insuranceName:'太平',	
				// values:[1000,2000,3000,4000,5000,6000,7000],
        values:{
          allnum:100,
          num2:200,
          num3:300
        },
        values2:[]
		  },		
	 
	  ]
      //列表合计详情
    };
  },
  mounted() {
    
   
    // this.geshiTable() 
    this.getCompanies();
    this.getUnits();
    // let a = this.formatDate(new Date().getTime(),0);
    let a = new Date().getFullYear() + "-12";
    // this.time2 = a.substring(0,7);
    this.time2 = a;
    let b = new Date().getFullYear() + "-01";
    // let b = this.formatDate(new Date().getTime(),1);
    this.time1 = b;
    if (this.$route.query.beginDate || this.$route.query.endDate) {
      this.time1 = this.$route.query.beginDate;
      this.time2 = this.$route.query.endDate;
      if (this.$route.query.organizationId) {
        this.organizationUnitId = Number(this.$route.query.organizationId);
      }
      if (
        this.$route.query.insuranceId &&
        typeof this.$route.query.insuranceId == "string"
      ) {
        let arr1 = [];
        arr1.push(this.$route.query.insuranceId);
        this.Insurance = arr1;
      } else {
        this.Insurance = this.$route.query.insuranceId;
      }
      // console.log( typeof(this.$route.query.insuranceId) == 'string');
      // console.log('this.$route.query.insuranceId----1-------------------------------');
      // this.value5 = this.$route.query.queryData;
    }
    // this.getFirstData();
  },
  computed: {},
  watch: {
    $route(to, from) {
      this.time1 = this.$route.query.beginDate;
      this.time2 = this.$route.query.endDate;
      if (this.$route.query.organizationId) {
        this.organizationUnitId = Number(this.$route.query.organizationId);
      }
      if (
        this.$route.query.insuranceId &&
        typeof this.$route.query.insuranceId == "string"
      ) {
        let arr1 = [];
        arr1.push(this.$route.query.insuranceId);
        this.Insurance = arr1;
      } else {
        this.Insurance = this.$route.query.insuranceId;
      }
      // console.log(this.$route.query.insuranceId);
      // console.log('this.$route.query.insuranceId-----------------------------------');
      this.value5 = this.$route.query.queryData;
      this.getFirstData();
    }
  },
  created() {
   
  },
  methods: {
    // geshiTable(){
    //     let that = this
    //     setTimeout(function(){
    //       //  console.log(that.$refs)
    //       let tdObj = that.$refs
    //       console.log(tdObj)
    //       for(let k in tdObj){
    //         if(k.substring(12,) == '3m'||k.substring(12,) =='6m' ||k.substring(12,) == '9m' || k.substring(12,) == '12m'){
    //           let aa=tdObj[k]
    //           for(let i=0; i<aa.length; i++){
    //             // console.log(aa[i])
    //             aa[i].parentNode.parentNode.style.borderRight='1px solid #aeaeae'
    //           }
    //         }
    //       }
    //     },10)
    // },
    handleCommand(command) {
		
      this.value5 = command;
	  this.allSelect = this.options[command - 1].label;
	  console.log(command)
	  console.log(this.columns)
	//   console.log(this.columns.length)
	  for(let i=1; i<this.columns.length;i++){
		//   console.log(i)
		console.log(this.columns[i].items.slice(command-1,command))
		this.columns2[i].items = this.columns[i].items.slice(command-1,command)
	  }
    },
    //  <span style="float:left;">月份</span>
    // <span style="float:left;">保费(万元)</span>
    renderHeader(h, { column, $index }) {
      return (
        <div class="thHead">

          <span>保险公司</span>
        </div>
      );
    },
    //开始时间
    startdate() {
      var that = this;
      return {
        disabledDate(time) {
          if (that.time2 != "") {
            return time.getTime() > new Date(that.time2).getTime();
          }
        }
      };
    },
    //结束时间
    enddate() {
      var that = this;
      return {
        disabledDate(time) {
          return time.getTime() < new Date(that.time1).getTime();
        }
      };
    },
    // 格式化
    formatDate(time, mon) {
      var date = new Date(time);

      var year = date.getFullYear() - mon,
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      var newTime =
        year +
        "-" +
        (month < 10 ? "0" + month : month) +
        "-" +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour) +
        ":" +
        (min < 10 ? "0" + min : min) +
        ":" +
        (sec < 10 ? "0" + sec : sec);
      return newTime;
    },
    // 公司
    getCompanies() {
      let that = this;
      // let all = {
      //   letter: "",
      //   insurances: [{ insuranceName: "全部保险公司", id: "" }]
      // };
      let params = {};
      this.post(params, "services/app/common/GetGroupInsurances").then(rs => {
        console.log(rs);
        if (rs.success) {
          let result = rs.result.items;
          // result.unshift(all);
          that.companies = result;
        }
      });
    },
    // 机构
    getUnits() {
      let params = {};
      let all = {
        organizationName: "全部所属机构",
        organizationId: ""
      };
      this.post(params, "services/app/common/ChildOrganizations").then(rs => {
        console.log(rs);
        if (rs.success) {
          rs.result.unshift(all);
          this.treeData = rs.result;
        }
      });
    },
    // setSelectedId(val) {
    //   this.organizationUnitId = val;
    // },
    // getFirstData() {
    //   this.loading = true;
    //   let params = {
    //     beginDate: this.time1,
    //     endDate: this.time2,
    //     organizationId: this.organizationUnitId,
    //     insuranceId: this.Insurance,
    //     queryData: this.value5
    //   };
    //   this.post(params, "services/app/report/Insurances_Months").then(rs => {
    //     if (rs.success) {
          
        
    //       this.columns = rs.result.columns;
    //       this.geshiTable()
    //       this.loading = false;
    //       let arr = [];
    //       rs.result.columns.map(function(item) {
    //         arr = arr.concat(item.items);
    //       });
    //       this.month = arr;
    //       if(rs.result.item.length < 6){
    //         // console.log('-----sad------')
    //         // console.log(arr.length)
    //         let values = []
    //         for(let i = 0;i<arr.length;i++){
	// 								values.push({
    //                 totalPremium: null, 
    //                 totalNetPremium: null, 
    //                 incomes: null, 
    //                 expends: null, 
    //                 profit: null,
    //                 profitRate:null
	// 								},)
							
	// 					}
    //         let bbVal = []
    //         for(let j = 0; j <rs.result.item.length; j++){
    //           bbVal.push(rs.result.item[j])
    //         }
	// 					for(let k = 0; k< 6-rs.result.item.length; k++){
    //           let total={
    //             totalPremium: null, 
    //             totalNetPremium: null, 
    //             incomes: null, 
    //             expends: null, 
    //             profit: null,
    //             profitRate:null
    //             }

    //           bbVal.push({
    //             insuranceId: "", insuranceName: "",
    //             total:total,
    //             values:values
    //             })
    //         }
	// 			this.tableData3 = bbVal;
    //       }else{
    //           this.tableData3 = rs.result.item;  
    //       }


          
    //       console.log("dsadsadad");
    //       // console.log(arr)
    //       console.log(this.columns);

          
    //     } else {
    //       this.loading = false;
    //       this.$notify.error({
    //         title: "错误",
    //         message: rs.error.message
    //       });
    //     }
    //   });
    // },
    // 搜索
    toSearch() {
      
      if (this.time1 != null && this.time2 != null) {
        this.$router.push({
          name: "pmonthform",
          query: {
            beginDate: this.time1,
            endDate: this.time2,
            organizationId: this.organizationUnitId,
            insuranceId: this.Insurance,
            queryData: this.value5,
            time: new Date().getTime()
          }
        });
      } else {
        this.$message.error("请输入出单时间");
      }
    },
    toexport() {},
    //跳转到日报表
    toDayForm(ins, date, col) {
      //  console.log(ins)
      //  date = date.slice(0,-1);
      //  console.log(date);
      //  var T = new Date();
      //  var year = T.getFullYear();
      //  var time = year+'-'+date;
      //  console.log(time);
      var mon =
        Number(date.replace("月", "")) > 9
          ? Number(date.replace("月", ""))
          : "0" + Number(date.replace("月", ""));
      var mon2 = col.value.substring(0, 4) + "-" + mon;
      this.$router.push({
        name: "dayform",
        query: { ins: ins, month: mon2, org: this.organizationUnitId }
      });
    },
    toMonthForm(ins) {
      console.log(ins);
      this.$router.push({
        name: "monthform",
        query: {
          ins: ins,
          beginDate: this.time1,
          endDate: this.time2,
          org: this.organizationUnitId
        }
      });
    },
    //导出
    exportForm() {
      let params = {
        beginDate: this.time1,
        endDate: this.time2,
        organizationId: this.organizationUnitId,
        insuranceId: this.Insurance,
        queryData: this.value5
      };
      this.post(params, "services/app/report/Insurances_Months_Export").then(
        rs => {
          if (rs.success) {
            let filePath = rs.result.filePath;
            console.log(filePath);
            window.location.href = filePath;
          } else {
            this.loading = false;
            this.$notify.error({
              title: "错误",
              message: rs.error.message
            });
          }
        }
      );
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss"  scoped>
.ishover:hover {
  // color:red;
  font-weight: 600;
  border-bottom: 1px dotted #333;
}
.brC{
  border-right:1px solid #AEAEAE;
}
.wd60 {
  width: 60px;
}
.wd70 {
  width: 70px;
}
.wd90 {
  width: 90px;
}
.wd93 {
  width: 93px;
}
.wd120 {
  width: 120px;
}
.wd210 {
  width: 160px;
}
.wid {
  width: 160px;
}
.wid1 {
  width: 160px;
}
.wd230 {
  width: 230px;
}
.app-box {
  color: #333;
  .day-top {
    margin-bottom: 30px;
    color: #666;
    .top {
      float: left;
      width: 300px;
      margin-right: 20px;
    }
    .top_1 {
      width: 32%;
    }
    .top1 {
      float: left;
      width: 230px;
      margin-right: 20px;
    }
    .top2 {
      float: left;
      width: 230px;
      margin-right: 20px;
    }
    .day-dropdown {
      float: right;
    }
  }
}
.baofe1 {
  width: 400px;
  .baofeiDetail {
    width: 49%;
    display: inline-block;
    div {
      padding: 8px;
      display: inline-block;
    }
  }
  a {
    display: block;
    width: 100%;
    color: #027dca;
    font-size: 13px;
    margin-top: 5px;
  }
  a:hover {
    text-decoration: underline;
  }
}
.unitbox {
  height: 40px;
  line-height: 40px;
  span {
    font-weight: 600;
  }
}
</style>